//
//  FieldDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/10/26.
//  Copyright © 2020 王洋. All rights reserved.
//
#import <SDImageCache.h>
#import "CommonHallModel.h"
#import "CommonMenuModel.h"
#import "CommonSellerModule.h"

#import "FieldDetailBottomView.h"

#import "GKPhotoBrowser.h"

#import "NormalImageShowCell.h"
#import "CommonBannerTableCell.h"
#import "CommonBannerTableCell.h"

#import "FieldInfoCell.h"
#import "MenuListCell.h"
#import "PoftfilioWebCell.h"
#import "StoreDetailNormalSectionHeader.h"

#import "MenuSegmentViewController.h"

#import "MessageCenterViewController.h"
#import "SubmitFieldOrderViewController.h"
#import "ScheduleInquiryViewController.h"
#import "StoreHotelDetailViewController.h"

#import "FieldDetailViewController.h"
#import "SelectMenuViewController.h"

//快问
#import "TIIMQuickReplyCardModel.h"
#import "StoreQuickReplyView.h"

@interface FieldDetailViewController ()<UITableViewDelegate, UITableViewDataSource,GKPhotoBrowserDelegate,PoftfilioWebCellDelegate>

@property (nonatomic, strong) FieldDetailBottomView *bottomView;

@property (nonatomic, strong) CommonHallModel *hallModel;

@property (nonatomic, strong) NSMutableArray <CommonHallModel *>*dataArray;

@property (nonatomic, strong) NSMutableArray <CommonMenuModel *>*menuArray;

@property (nonatomic, assign) NSTimeInterval lastTime;

@property (nonatomic, strong)UITableView *tableview;

//快问
@property(nonatomic,strong)TIIMQuickReplyCardModel *quickReplyModel;
@property(nonatomic,strong)BaseAdjustButton *quickReplyButton;
@property(nonatomic,weak)StoreQuickReplyView *weakQuickReplyView;
@end

@implementation FieldDetailViewController


- (void)dealloc {
    NSLog(@"场地释放了");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self request_hallDetail];
}

- (void)initView {
    
    self.view.backgroundColor = UIColorHex(0xf0f0f0);
    [self initNavi];
    [self initViewAction];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableview];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(60 + Bottom_SafeHeight);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:@"BA_LoginSuccess" object:nil];

    [self.tableview reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleStep) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleStep) name:UIApplicationWillTerminateNotification object:nil];
    
    self.lastTime = [Utilities getCurrentServerTimestamp];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

    [self handleStep];
}

- (void)appBecomeActive {
    self.lastTime = [Utilities getCurrentServerTimestamp];
}

- (void)handleStep {
    [[BA_BusinessHelper shared] addFootPrintWith:self.bhId lastTime:self.lastTime And:self.hallModel.bhSellerId     type:BusinessCollectType_field];
}

- (void)loginSuccessAction {
    [self.tableview reloadData];
}
- (void)prepareData {
    CommonHallModel *detailModel = self.hallModel;
    //组合数据
    CommentRichTextModel *richTextModel = [[CommentRichTextModel alloc]init];
    richTextModel.richContent = detailModel.bhText;
    richTextModel.images = detailModel.imgTextList;
    detailModel.richTextModel = richTextModel;
    //组合数据
    //richContentAttriteStr、richTextFrame
    NSMutableAttributedString *titleAttributes = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",richTextModel.richContent]];
    titleAttributes.font = kFontRegular14;
    titleAttributes.color = kColor51;
    titleAttributes.lineSpacing = 5*ADAPTER_WIDTH;
    richTextModel.richContentAttriteStr = titleAttributes;
    richTextModel.richTextFrame = CGRectMake(10*ADAPTER_WIDTH, 10*ADAPTER_WIDTH, WIDTH - 20*ADAPTER_WIDTH, [YYTextLayout layoutWithContainerSize:CGSizeMake(WIDTH - 20*ADAPTER_WIDTH, MAXFLOAT) text:titleAttributes].textBoundingSize.height);
    
    //richImageModulesTop
    richTextModel.richImageModulesTop = richTextModel.richContent.length == 0 ? 10*ADAPTER_WIDTH : CGRectGetMaxY(richTextModel.richTextFrame) + 20*ADAPTER_WIDTH;
    //预先加载
    CGFloat cacheNumber = 0;
    CGFloat shouldLoadingNumber = 0;
    SDImageCache *cache = [SDImageCache sharedImageCache];
    CGFloat orinY = richTextModel.richImageModulesTop;
    for (NSInteger index = 0; index < richTextModel.images.count; index ++) {
        CommonMediaModel *mediaModel = richTextModel.images[index];
        UIImage *orinImage = [cache imageFromDiskCacheForKey:mediaModel.url];
        if ([cache diskImageDataExistsWithKey:mediaModel.url] && orinImage) {
            cacheNumber = cacheNumber + 1;
            mediaModel.itemHeight = WIDTH * orinImage.size.height / orinImage.size.width;
            orinY = orinY + mediaModel.itemHeight;
        } else {
            shouldLoadingNumber = shouldLoadingNumber + 1;
            mediaModel.itemHeight = 300*ADAPTER_WIDTH;
        }
    }
    if (richTextModel.images.count == 0) {
        richTextModel.richTextModulesHeight = orinY;
        richTextModel.allImagesCache = NO;
    } else {
        if (cacheNumber == richTextModel.images.count) {
            richTextModel.richTextModulesHeight = orinY;
            richTextModel.allImagesCache = YES;
        } else {
            CGFloat orinY = richTextModel.richImageModulesTop;
            orinY = orinY + richTextModel.images.count * richTextModel.images.firstObject.itemHeight;
            richTextModel.richTextModulesHeight = orinY;
            richTextModel.allImagesCache = NO;
            //预先加载把
            for (NSInteger index = 0; index < richTextModel.images.count; index ++) {
                NSString *url = richTextModel.images[index].url;
                [[[UIImageView alloc]init]sd_setImageWithURL:url.wppURL completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    
                }];
            }
        }
    }
}

- (void)initNavi {
    
    self.title = self.hallModel.bhName;

    UIButton *imBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    imBtn.frame = CGRectMake(0,0,40,30);
    [imBtn setImage:[UIImage imageNamed:@"field_xiaoxi"] forState:UIControlStateNormal];
    [imBtn addTarget:self action:@selector(goIm) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *imItem = [[UIBarButtonItem alloc] initWithCustomView:imBtn];
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(0,0,40,30);
    [shareBtn setImage:[UIImage imageNamed:@"field_fenxiang"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItems =@[imItem,shareItem];
    
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            imBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            imBtn.badgeBGColor = [UIColor redColor];
        } else {
            imBtn.badgeValue = @"";
            imBtn.badgeBGColor = [UIColor clearColor];
        }
    }];
}

- (void)goIm {
    MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)shareAction {
    [self share];
}

#pragma mark Share
- (void)share {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?goodsId=%@&myCode=%@",BA_GlobalH5_Domain,@"/fieldDetail",self.hallModel.bhId,[TTUserModel sharedObject].myCode];
    model.title = self.hallModel.bhName;
    model.content = @"婚前婚后邀您体验";
    
    if (self.hallModel.headUrlList.count > 0) {
        model.image = self.hallModel.headUrlList.firstObject;
    }
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)initViewAction {
    
    WEAKSELF
    self.bottomView.FieldDetailBottomViewBlock = ^(FieldDetailBottomType type) {
        
        switch (type) {
            case FieldDetailBottomType_store:{
                StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
                vc.storeId = weakSelf.hallModel.bhSellerId;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } break;
            case FieldDetailBottomType_im:{
                [[TT_IMContactManager manager] ImContactWithStoreId:weakSelf.hallModel.bhSellerId];
            } break;
            case FieldDetailBottomType_call:{
                [[TT_PhonaCallManager manager] callWithStoreId:weakSelf.hallModel.bhSellerId];
            } break;
            case FieldDetailBottomType_schedule:{
                ScheduleInquiryViewController *vc = [[ScheduleInquiryViewController alloc] init];
                vc.packageId = weakSelf.hallModel.bhId;
                vc.sellerId = weakSelf.hallModel.bhSellerId;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } break;
            case FieldDetailBottomType_order:{
                [weakSelf goFieldOrder];
            } break;
            default:
                break;
        }
    };
}

- (void)goFieldOrder {

    if (self.menuArray.count == 0) {
        
        [SVProgressHUD showErrorWithStatus:@"该场地没有菜单无法下单"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    SelectMenuViewController *vc = [[SelectMenuViewController alloc] init];
    vc.model = self.hallModel;
    vc.menuArray = self.menuArray;
    [self.navigationController pushViewController:vc animated:YES];
    
//    SubmitFieldOrderViewController *vc = [[SubmitFieldOrderViewController alloc] init];
//    vc.model = self.hallModel;
//    vc.menuArray = self.menuArray;
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;//这个1是评价，这个评价是动态的
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    switch (section) {
        case FieldSub_sectionType_mainImage:{
            return 1;
        } break;
        case FieldSub_sectionType_info:{
            return 1;
        } break;
        case FieldSub_sectionType_imageAndText:{
            return 1;
        } break;
        case FieldSub_sectionType_menuList:{
            return 1;
        } break;
        default:
            break;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case FieldSub_sectionType_mainImage:{
            return TTScreenWidth * 0.5 ;
        } break;
        case FieldSub_sectionType_info:{
            
            if (self.hallModel.paramArray.count > 0) {
                return (self.hallModel.paramArray.count/2 + 2) * 32;
            } else {
                return CGFLOAT_MIN;
            }

        } break;
        case FieldSub_sectionType_imageAndText:{
            return _hallModel.richTextModel.richTextModulesHeight;

        } break;
        case FieldSub_sectionType_menuList:{
            if (self.menuArray.count > 0) {
                return 180;
            } else {
                return CGFLOAT_MIN;
            }
        } break;
        default:
            break;
    }
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    switch (section) {
        case FieldSub_sectionType_mainImage:{
            return CGFLOAT_MIN;
        } break;
        case FieldSub_sectionType_info:{
            if (self.hallModel.paramArray.count > 0) {
                return 50;
            } else {
                return CGFLOAT_MIN;
            }
        } break;
        case FieldSub_sectionType_imageAndText:{
            return 50;
        } break;
        case FieldSub_sectionType_menuList:{
            if (self.menuArray.count > 0) {
                return 50;
            } else {
                return CGFLOAT_MIN;
            }
        } break;
        default:
            break;
    }
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        
    StoreDetailNormalSectionHeader *headView  =  [[NSBundle mainBundle] loadNibNamed:@"StoreDetailNormalSectionHeader"owner:nil options:nil].firstObject;
    
    switch (section) {
        case FieldSub_sectionType_mainImage:{
        } break;
        case FieldSub_sectionType_info:{
            headView.sectionTitle.text = self.hallModel.bhName;
            headView.sectionContent.text = @"";
        } break;
        case FieldSub_sectionType_imageAndText:{
            headView.sectionTitle.text = @"场地展示";
            headView.sectionContent.text = @"";
        } break;
        case FieldSub_sectionType_menuList:{
            headView.sectionTitle.text = @"婚宴菜单";
            headView.sectionContent.text = @"";
        } break;
        default:
            break;
    }
    
    return  headView;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    switch (indexPath.section) {
        case FieldSub_sectionType_mainImage:{
            CommonBannerTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonBannerTableCellID"];

            [cell configBannerCellWithImageArray:self.hallModel.headUrlList];
            
            cell.CycleImgClickedBlock = ^(NSInteger index) {
                if (weakSelf.hallModel.headUrlList.count > 0) {
                    [weakSelf showImageWithArray:weakSelf.hallModel.headUrlList index:index];
                }
            };
            return cell;
            
        } break;
        case FieldSub_sectionType_info:{
            FieldInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FieldInfoCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            if (self.hallModel.paramArray.count > 0) {
                [cell fillCellWithArray:self.hallModel.paramArray];
            }
            
            return cell;
        } break;
        case FieldSub_sectionType_imageAndText:{
            
            PoftfilioWebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PoftfilioWebCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            if (_hallModel) {
                cell.richTextModel = self.hallModel.richTextModel;
            }
            cell.parentVC = self;
            return cell;
        } break;
        case FieldSub_sectionType_menuList:{
            MenuListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MenuListCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.menuArray];
            
            WEAKSELF
            __weak typeof(cell) weakCell = cell;
            cell.MenuListCellLoginBlock = ^{
              
                [weakSelf openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                    if (isLogin) {
                        [weakCell.collectionview reloadData];
                    }
                }];
            };
            
            cell.MenuListCellBlock = ^(NSInteger index) {
              
                MenuSegmentViewController *vc = [[MenuSegmentViewController alloc] init];
                vc.selectIndex = index;
                vc.menuArray = self.menuArray;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            };
            return cell;
        } break;
        default:
            break;
    }
    
    
    NormalImageShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NormalImageShowCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case FieldSub_sectionType_mainImage:{
        } break;
        case FieldSub_sectionType_info:{
        } break;
        case FieldSub_sectionType_imageAndText:{
        } break;
        case FieldSub_sectionType_menuList:{
        } break;
        default:
            break;
    }
}
#pragma mark - PoftfilioWebCell
- (void)poftfilioWebCellBackHeight:(CGFloat)cellHeight
{
    _hallModel.richTextModel.richTextModulesHeight = cellHeight;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview reloadData];
    });
}

- (void)showImageWithArray:(NSArray *)imageUrls index:(NSInteger)index {
    NSMutableArray *photos = [NSMutableArray new];
    
    [imageUrls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:obj];
        [photos addObject:photo];
    }];
    
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    
    browser.delegate  = self;
    [browser showFromVC:self];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        _tableview.showsVerticalScrollIndicator = NO;
        
        [_tableview registerNib:[UINib nibWithNibName:@"NormalImageShowCell" bundle:nil]
         forCellReuseIdentifier:@"NormalImageShowCellID"];

        [_tableview registerClass:[CommonBannerTableCell class] forCellReuseIdentifier:@"CommonBannerTableCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"FieldInfoCell" bundle:nil]
         forCellReuseIdentifier:@"FieldInfoCellID"];
        
        [_tableview registerClass:[PoftfilioWebCell class] forCellReuseIdentifier:@"PoftfilioWebCellID"];

     
        [_tableview registerNib:[UINib nibWithNibName:@"MenuListCell" bundle:nil]
         forCellReuseIdentifier:@"MenuListCellID"];
        
    }
    return _tableview;
}

- (CommonHallModel *)hallModel {
    if (!_hallModel) {
        _hallModel = [[CommonHallModel alloc] init];
    }
    return _hallModel;
}

- (NSMutableArray<CommonMenuModel *> *)menuArray {
    if (!_menuArray) {
        _menuArray = @[].mutableCopy;
    }
    return _menuArray;
}

- (FieldDetailBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"FieldDetailBottomView"owner:nil options:nil].firstObject;
    }
    return _bottomView;
}

- (void)request_hallDetail {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.bhId forKey:@"bhId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_HallInfo];
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];

                if ([list isKindOfClass:[NSArray class]]) {
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        CommonHallModel *hallModel = [CommonHallModel modelWithDictionary:listDic];
                        hallModel.images = @[].mutableCopy;

                        NSArray *headList = [listDic valueForKey:@"headList"];
                        if ([headList isKindOfClass:[NSArray class]]) {
                            hallModel.headList = @[].mutableCopy;
                            hallModel.headUrlList = @[].mutableCopy;
                            for (int j = 0; j < headList.count; j++) {
                                NSDictionary *headDic = headList[j];
                                CommonMediaModel *mediaModel = [CommonMediaModel modelWithDictionary:headDic];
                                if (mediaModel.url.length > 0) {
                                    [hallModel.headUrlList addObject:mediaModel.url];
                                }
                                [hallModel.sysMediaList addObject:mediaModel];
                            }
                        }

                        NSArray *sysMediaList = [listDic valueForKey:@"imgTextList"];
                        if ([sysMediaList isKindOfClass:[NSArray class]]) {
                            hallModel.sysMediaList = @[].mutableCopy;
                            for (int j = 0; j < sysMediaList.count; j++) {
                                NSDictionary *mediaDic = sysMediaList[j];
                                CommonMediaModel *mediaModel = [CommonMediaModel modelWithDictionary:mediaDic];
                                if (mediaModel.url.length > 0) {
                                    [hallModel.images addObject:mediaModel.url];
                                }
                                [hallModel.sysMediaList addObject:mediaModel];
                            }
                        }

                        NSDictionary *sellerGoodsServiceFlag = [listDic valueForKey:@"sellerGoodsServiceFlag"];
                        if ([sellerGoodsServiceFlag isKindOfClass:[NSDictionary class]]) {

                            NSString *sgsServiceParameter = [sellerGoodsServiceFlag valueForKey:@"sgsServiceParameter"];
                            NSString *type3 = [sellerGoodsServiceFlag valueForKey:@"type3"];
                            NSString *type7 = [sellerGoodsServiceFlag valueForKey:@"type7"];

                            hallModel.type3 = type3;
                            hallModel.type7 = type7;

                            if (sgsServiceParameter.length > 0) {
                                hallModel.sgsServiceParameter = sgsServiceParameter;
                                hallModel.paramArray = @[].mutableCopy;

                                NSString *jsonString = hallModel.sgsServiceParameter;
                                if (jsonString.length > 3) {

                                    NSMutableDictionary* jsonDic = @{}.mutableCopy;
                                    jsonDic = [weakSelf convert2DictionaryWithJSONString:jsonString].mutableCopy;

                                    NSString *jsonKey = jsonDic.allKeys.firstObject;
                                    NSDictionary *dic = [jsonDic valueForKey:jsonKey];

                                    if ([dic isKindOfClass:[NSDictionary class]]) {
                                        for (int j = 0; j < dic.allKeys.count; j++) {
                                            CommonServiceModel *paramModel = [[CommonServiceModel alloc] init];
                                            paramModel.itemTitle = dic.allKeys[j];
                                            paramModel.itemContent = dic.allValues[j];
                                            [hallModel.paramArray addObject:paramModel];
                                        }
                                    }
                                }
                            }
                        }

                        [weakSelf.dataArray addObject:hallModel];
                    }
                }
                
                if (weakSelf.dataArray.count > 0) {
                    weakSelf.hallModel = weakSelf.dataArray.firstObject;
                    [weakSelf request_menuList:weakSelf.hallModel.bhSellerId];
                }
                
                [weakSelf prepareData];
                [weakSelf initView];

                if ([TTUserModel sharedObject].userId.length > 0) {
                    [weakSelf addQuickReply];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];

    }];
}

//API_MenuList
- (void)request_menuList:(NSString *)sellerId {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(1) forKey:@"pageNum"];
    [dic setValue:@(100) forKey:@"pageSize"];

    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:sellerId forKey:@"bhmSellerId"];
    
    [dic setValue:t forKey:@"t"];
    
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MenuList];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                NSArray *list = [resultDic valueForKey:@"list"];

//                if ([list isKindOfClass:[NSArray class]]) {
//
//                    for (int i = 0; i < list.count; i++) {
//                        NSDictionary *listDic = list[i];
//                        CommonMenuModel *packageModel = [CommonMenuModel modelWithDictionary:listDic];
//                        [weakSelf.menuArray addObject:packageModel];
//                    }
//                }
                
                weakSelf.menuArray = @[].mutableCopy;
                if ([list isKindOfClass:[NSArray class]]) {
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *sellerBanquetHallMenuListDic = list[i];
                        CommonMenuModel *menuModel = [CommonMenuModel modelWithJSON:sellerBanquetHallMenuListDic];
                        menuModel.bhmMenuCount = 1;

                        menuModel.dishesList = @[].mutableCopy;
                        NSArray *f_dishesList = [sellerBanquetHallMenuListDic valueForKey:@"dishesList"];
                        if ([f_dishesList isKindOfClass:[NSArray class]]) {
                            for (NSDictionary *f_disDic in f_dishesList) {
                                V2CommonMenuModel *f_model = [V2CommonMenuModel modelWithJSON:f_disDic];
                                f_model.dishesList = @[].mutableCopy;
                                
                                if ([f_disDic isKindOfClass:[NSDictionary class]]) {
                                    NSArray *s_dishesList = [f_disDic valueForKey:@"dishesList"];
                                    if ([s_dishesList isKindOfClass:[NSArray class]]) {
                                        for (NSDictionary *s_disDic in s_dishesList) {
                                            V2CommonMenuModel *s_model = [V2CommonMenuModel modelWithJSON:s_disDic];
                                            [f_model.dishesList addObject:s_model];
                                        }
                                    }
                                    [menuModel.dishesList addObject:f_model];
                                }
                            }
                        }
                        [weakSelf.menuArray addObject:menuModel];
                    }
                }                
                [weakSelf.tableview reloadData];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}


- (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"%@",err);
        return nil;
    }
    return dic;
}
#pragma mark - 快捷回复模块
- (void)addQuickReply
{
    dispatch_async(dispatch_get_main_queue(), ^{
        //获取快捷回复
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setValue:[NSString stringWithFormat:@"%@",self.hallModel.bhSellerId] forKey:@"sellerId"];
        WK(weakSelf)
        [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/userProblem/userSelectList"] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
            //NSLog(@"%@",responseObject);
            TIIMQuickReplyCardModel *responModel = [TIIMQuickReplyCardModel modelWithJSON:responseObject];
            if (responModel.success) {
                if (responModel.data.count > 0) {
                    weakSelf.quickReplyModel = responModel;
                    [weakSelf quickReplyButton];
                }
            } else {
                
            }
        } FailedBlock:^(NSError * _Nonnull error) {
            
        }];
    });
}
- (BaseAdjustButton *)quickReplyButton
{
    if (!_quickReplyButton) {
        BaseAdjustButton *button = [BaseAdjustButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:button];
        button.type = layoutTypeHorizontalLeftImageRightTitle;
        button.imageWidth = 10*ADAPTER_WIDTH;
        button.imageHeight = 6*ADAPTER_WIDTH;
        button.title = @"快问";
        button.fontWeight = UIFontWeightMedium;
        button.fontSize = 13*ADAPTER_WIDTH;
        button.marginLeft = 10*ADAPTER_WIDTH;
        button.marginItemX = 4*ADAPTER_WIDTH;
        button.marginRight = 10*ADAPTER_WIDTH;
        button.marginTop = 10*ADAPTER_WIDTH;
        button.marginBottom = 10*ADAPTER_WIDTH;
        [button begin];
        button.right = WIDTH - 16*ADAPTER_WIDTH;
        button.bottom = HEIGHT - 150*ADAPTER_WIDTH - kBottomSafeHeight;
        button.backgroundColor = rgba(0, 0, 0, 0.8);
        button.backgroundColor = rgba(76, 198, 253, 1);
        [button setTitleColor:WhiteColor forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"QuickReply_up"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"QuickReply_down"] forState:UIControlStateSelected];
        [button setTitle:@"快问" forState:UIControlStateNormal];
        [button setTitle:@"收起" forState:UIControlStateSelected];
        [button addTarget:self action:@selector(clickQuickReplyButton:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = button.height * 0.5;
        button.layer.masksToBounds = YES;
        _quickReplyButton = button;
    }
    return _quickReplyButton;
}
- (void)clickQuickReplyButton:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        sender.backgroundColor = rgba(0, 0, 0, 0.8);
        [sender setImage:[UIImage imageNamed:@"QuickReply_dwon"] forState:UIControlStateNormal];
        
        StoreQuickReplyView *view = [[StoreQuickReplyView alloc]initWithFrame:CGRectZero withParent:self withReplyButton:sender];
        view.quickReplyModel = self.quickReplyModel;
        WK(weakSelf)
        [view setCallBackContentBlock:^(NSString * _Nonnull content) {
            [weakSelf gotoChatWithContent:content];
        }];
        self.weakQuickReplyView = view;
    } else {
        sender.backgroundColor = rgba(76, 198, 253, 1);
        [sender setImage:[UIImage imageNamed:@"QuickReply_up"] forState:UIControlStateNormal];
        if (_weakQuickReplyView) {
            [self.weakQuickReplyView dismiss];
        }
    }
}
- (void)gotoChatWithContent:(NSString *)content
{
    NSLog(@"%@",content);
    [[TT_IMContactManager manager] ImContactWithStoreId:self.hallModel.bhSellerId withQuickReply:content];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //NSLog(@"scrollViewDidEndDecelerating");
    if (_quickReplyButton) {
        WK(weakSelf)
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.quickReplyButton.right = WIDTH - 16*ADAPTER_WIDTH;
        }];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //NSLog(@"scrollViewDidEndDragging");
    if (_quickReplyButton) {
        WK(weakSelf)
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.quickReplyButton.right = WIDTH - 16*ADAPTER_WIDTH;
        }];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (_quickReplyButton) {
        WK(weakSelf)
        CGFloat right = WIDTH + (weakSelf.quickReplyButton.width - 24*ADAPTER_WIDTH);
        [UIView animateWithDuration:0.2 animations:^{
            weakSelf.quickReplyButton.right = right;
        }];
    }
}
@end
